package fr.ecp.sio.cloudatlas;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import fr.ecp.sio.model.User;

/**
 * Servlet implementation class SignUpUserServlet
 */
@WebServlet("/SignUpUserServlet")
public class SignUpUserServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public SignUpUserServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String email = request.getParameter("email");
		String password = request.getParameter("password");
		String confirmPassword = request.getParameter("confirmPassword");
		String accountType = "standard";

		User user = new User(email, password);
		if (!user.exists()) {

			user.createOnDB();
			Cookie loginCookie = new Cookie("userEmail", user.getEmail());
			Cookie loginTypeCookie;
			System.out.println("Correct user");
			loginTypeCookie = new Cookie("userType", "standard");
			// setting cookie to expiry in 30 mins
			loginCookie.setMaxAge(30 * 60);
			loginTypeCookie.setMaxAge(30 * 60);
			response.addCookie(loginCookie);
			response.addCookie(loginTypeCookie);
			RequestDispatcher dispatcher = request
					.getRequestDispatcher("SearchServlet");
			dispatcher.forward(request, response);

		} else {
			RequestDispatcher dispatcher = request
					.getRequestDispatcher("signupUser.jsp");
			dispatcher.forward(request, response);
		}

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
